package com.base.cn.platform.os.statistics;

import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.service.manage.statistics.flow.ZStatisticsTerminalUVCountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 终端用户访问PV统计工具
 *
 * @author s.li
 * @date 2019/04/29
 */
@Slf4j
public class TerminalUtils {

    /**
     * 用户使用终端UV统计
     * @param terminalUVCountService
     */
    public static void terminalUVStatistics(ZStatisticsTerminalUVCountService terminalUVCountService){
        try{
            File classPathDir = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX);
            File logsFileDir = new File(classPathDir,"/static/logs/terminal");
            if(logsFileDir.exists()){
                String[] fileNameArr = logsFileDir.list();
                List<String> fileNameList = new ArrayList<>();
                if(ObjectUtils.isNotEmpty(fileNameArr)){
                    String exFileName = "terminal-pv-"+ DateUtils.format(new Date(),"yyyy-MM-dd-HH")+".log";
                    List<String> logFileLineContextList = LogFileUtils.getLogFileLineContextList(logsFileDir,fileNameList,fileNameArr,exFileName);
                    //处理日志文件内容
                    List<Map<String,Object>> uvDataList = handleUVLogsContext(logFileLineContextList);
                    if(ObjectUtils.isNotEmpty(uvDataList)){
                        Map<String,Object> resultMap = terminalUVCountService.genTerminalUVCount(uvDataList);
                        //删除文件
                        LogFileUtils.deleteLogFile(resultMap,logsFileDir,fileNameList);
                    }
                }
            }
        }catch (Exception e){
            log.error("terminalUVStatistics()--error",e);
        }
    }

    /**
     * (UV)处理日志文件内容
     * @param logFileLineContextList 内容列表，第个元素是日志文件中一行
     * @return List<Map<String,Object>>
     */
    private static List<Map<String,Object>> handleUVLogsContext(List<String> logFileLineContextList){
        if(ObjectUtils.isNotEmpty(logFileLineContextList)){
            List<Map<String,String>> mapList = getMapDataList(logFileLineContextList);
            if(ObjectUtils.isNotEmpty(mapList)){
                Map<String,List<Map<String,String>>> stringListMap = mapList.stream().collect(Collectors.groupingBy(e->e.get("tenantId")));
                List<Map<String,String>> dataList = stringListMap.get("0");
                List<Map<String,Object>> terminalUVDataList = new ArrayList<>();
                if(ObjectUtils.isNotEmpty(dataList)){
                    //以天分组
                    Map<String,List<Map<String,String>>> listMap = dataList.stream().collect(Collectors.groupingBy(e->e.get("time")));
                    listMap.forEach((k,list)->{
                        //以终端类型分组
                        Map<String,List<Map<String,String>>> terminalTypeMapList =list.stream().collect(Collectors.groupingBy(e->e.get("terminalType")));
                        Map<String,Object> map = new HashMap<>();
                        map.put("countTime", DateUtils.parseDate(k,"yyyy-MM-dd"));
                        map.put("uvCount", 0);
                        terminalTypeMapList.forEach((terminalType,userList)->{
                            //得到用户量
                            int count = userList.stream().collect(Collectors.groupingBy(e->e.get("userId"))).size();
                            if(terminalType.equals("Windows")){
                                map.put("windowCount", count);
                            }else if(terminalType.equals("Mac")){
                                map.put("macCount", count);
                            }else if(terminalType.equals("Android")){
                                map.put("andCount", count);
                            }else if(terminalType.equals("IOS")){
                                map.put("iosCount", count);
                            }else if(terminalType.equals("Other")){
                                map.put("otherCount", count);
                            }
                            int uvCount = (int)map.get("uvCount") + count;
                            map.put("uvCount",uvCount);
                        });
                        terminalUVDataList.add(map);
                    });
                    return terminalUVDataList;
                }
            }
        }
        return null;
    }

    /**
     * 获取日志数据
     * @param logFileLineContextList
     * @return
     */
    private static List<Map<String,String>> getMapDataList(List<String> logFileLineContextList){
        List<Map<String,String>> mapList = new ArrayList<>();
        logFileLineContextList.forEach(lineContext->{
            String[] arr = lineContext.split("\\|");
            String userId = arr[0];
            String time = arr[1];
            String terminalType = arr[2];
            String tenantId = arr[3];
            Map<String,String> map = new HashMap<>();
            map.put("userId",userId);
            map.put("time",time);//只取到天部分的时间
            map.put("terminalType",terminalType);//终端类型
            map.put("tenantId",tenantId);
            mapList.add(map);
        });
        return mapList;
    }
}
